﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraEditors;

using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesRaster;


namespace SZ
{
    public partial class MainFrm : RibbonForm
    {
        public IWorkspace pWorkspace;

        public MainFrm()
        {
            InitializeComponent();
            ConnectSDE connectSde = new ConnectSDE();
            pWorkspace = connectSde.SdeWorkspace();
            CreateTreeView(pWorkspace);

            //右键菜单
            ContextMenu contextMenu = new ContextMenu(this, this.axMapControl1, this.axTOCControl1, this.treeView1);
            contextMenu.CreateContextMenu();

        }

        #region 文件

        private void newBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            DocumentMapManageClass.CreateMapDocument(axMapControl1);
        }

        private void openBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            DocumentMapManageClass.OpenMapDocument(axMapControl1);
        }

        private void saveAsToBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            DocumentMapManageClass.SaveAsMapDocument(axMapControl1);
        }

        private void addDataBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            AddDataDialogFrm addDataDialog = new AddDataDialogFrm(axMapControl1);
            addDataDialog.Show();
        }

        #endregion

        #region 工具

        //放大
        private void zoomInBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pZoomIn = new ControlsMapZoomInTool();
            pZoomIn.OnCreate(axMapControl1.Object);
            axMapControl1.CurrentTool = pZoomIn as ITool;
        }

        //缩小
        private void zoomOutBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pZoomOut = new ControlsMapZoomOutTool();
            pZoomOut.OnCreate(axMapControl1.Object);
            axMapControl1.CurrentTool = pZoomOut as ITool;
        }

        //移动
        private void panBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pPan = new ControlsMapPanToolClass();
            pPan.OnCreate(axMapControl1.Object);
            axMapControl1.CurrentTool = pPan as ITool;
        }

        //全图
        private void fullExtentBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pFullExtent = new ControlsMapFullExtentCommandClass();
            pFullExtent.OnCreate(axMapControl1.Object);
            pFullExtent.OnClick();
        }

        //前景
        private void preViewBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pPreView = new ControlsMapZoomToLastExtentBackCommandClass();
            pPreView.OnCreate(axMapControl1.Object);
            pPreView.OnClick();
        }

        //后景
        private void lastViewBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ICommand pLastView = new ControlsMapZoomToLastExtentForwardCommandClass();
            pLastView.OnCreate(axMapControl1.Object);
            pLastView.OnClick();
        }

        //识别
        private void identifyBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            IdentifyClass identify = new IdentifyClass(this, this.axMapControl1);
            identify.OnCreate(axMapControl1.Object);
            axMapControl1.CurrentTool = identify as ITool;
        }

        #endregion

        #region 数据库目录

        //载入SDE中的目录树
        private void CreateTreeView(IWorkspace pWorkspace)
        {
            //要素集
            treeView1.ImageList = imageList1;
            IEnumDatasetName pEnumDatasetName;
            pEnumDatasetName = pWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureDataset);
            IDatasetName pFeatureDatasetName;

            pEnumDatasetName.Reset();
            pFeatureDatasetName = pEnumDatasetName.Next();

            string name;
            while (pFeatureDatasetName != null)
            {
                name = pFeatureDatasetName.Name;
                TreeNode node = new TreeNode(name);
                treeView1.Nodes.Add(node);
                node.Nodes.Add("1");  // 任意添加一个子节点，目的是出现父节点前的加号，之后在展开父节点时再删除此节点
                
                node.ImageIndex = 0;
                node.StateImageIndex = 0;
                node.Tag = 2;
                pFeatureDatasetName = pEnumDatasetName.Next();
            }

            //栅格目录
            pEnumDatasetName = pWorkspace.get_DatasetNames(esriDatasetType.esriDTRasterCatalog);
            IDatasetName pRasterCatalogName;
            pRasterCatalogName = pEnumDatasetName.Next();
            while (pRasterCatalogName != null)
            {
                name = pRasterCatalogName.Name;
                TreeNode node = new TreeNode(name);
                treeView1.Nodes.Add(node);
                node.Tag = 1;
                node.ImageIndex = 1;
                node.StateImageIndex = 1;
                node.Nodes.Add("1");
                pRasterCatalogName = pEnumDatasetName.Next();
            }
            //要素
            pEnumDatasetName = pWorkspace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
            pEnumDatasetName.Reset();
            IDatasetName pFeatureClassName;
            pFeatureClassName = pEnumDatasetName.Next();

            while (pFeatureClassName != null)
            {
                name = pFeatureClassName.Name;
                TreeNode node = new TreeNode(name);
                treeView1.Nodes.Add(node);
                node.ImageIndex = 2;
                node.SelectedImageIndex = 2;
                pFeatureClassName = pEnumDatasetName.Next();
            }
        }

        //判断同级节点是否全部选中
        private void subParentChecked(TreeNode node)
        {
            if (node.Parent != null)
            {
                foreach (TreeNode n in node.Parent.Nodes)
                {
                    if (n.Checked == false)
                        return;
                }
                node.Parent.Checked = true;
            }
        }

        //判断同级节点是否全部取消
        private void subParentUnchecked(TreeNode node)
        {
            if (node.Parent != null)
            {
                foreach (TreeNode n in node.Parent.Nodes)
                {
                    if (n.Checked == true)
                        return;
                }
                node.Parent.Checked = false;
            }
        }

        //遍历树中的所有节点
        public void ShowAllNodes(TreeNodeCollection nodes, string name)
        {
            foreach (TreeNode treeNode in nodes)
            {
                if (treeNode.Nodes.Count > 0)
                {
                    ShowAllNodes(treeNode.Nodes, name);

                }
                else
                {
                    if (treeNode.Text == name)
                    {
                        treeNode.Checked = false;

                    }

                }
            }
        }

        //根据名称查询数据库中的要素
        private void SearchFeatureDataset(string name, IWorkspace pWorkspace)
        {
            #region 要素
            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
            IFeatureClass pSearchFeatureClass;
            IFeatureLayer pFeatureLayer = new FeatureLayerClass();

            pSearchFeatureClass = pFeatureWorkspace.OpenFeatureClass(name);
            pFeatureLayer.Name = pSearchFeatureClass.AliasName;
            pFeatureLayer.FeatureClass = pSearchFeatureClass;
            if (pFeatureLayer != null)
            {

                axMapControl1.AddLayer(pFeatureLayer);
                axMapControl1.Refresh();
            }
            else
            {
                MessageBox.Show("请选择有效的图层！");
            }
            #endregion



        }
        //根据名称查找栅格数据
        private void SearchRasterDataset(string parentName, string name, IWorkspace pWorkspace)
        {
            IRasterWorkspaceEx pRasterWorkspaceEx = pWorkspace as IRasterWorkspaceEx;
            IRasterCatalog pRasterCatalog = pRasterWorkspaceEx.OpenRasterCatalog(parentName);
            //IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(parentName);
            IDataset pDataset = pRasterCatalog as IDataset;
            IEnumDataset pEnumDataset = pDataset.Subsets;
            pEnumDataset.Reset();
            IDataset pSubDataset = pEnumDataset.Next();

            ITable pTable = pRasterCatalog as ITable;

            int index = pTable.FindField("NAME");
            IRow pRow = null;
            ICursor pRasterCursor = pTable.Search(null, false);
            pRow = pRasterCursor.NextRow();
           
            while (pRow != null)
            {
                if (pRow.get_Value(index).ToString () == name)
                {
                    IRasterLayer pRasterLayer = new RasterLayerClass();

                    pRasterLayer.CreateFromDataset(pSubDataset as IRasterDataset);
                    this.axMapControl1.AddLayer(pRasterLayer);
                    this.axMapControl1.Refresh();
                    return;
                }
                
                pRow = pRasterCursor.NextRow();
                pSubDataset = pEnumDataset.Next();
            }
        }

        //删除对应的图层
        private void DeletedLayer(string name)
        {
            int index = axMapControl1.LayerCount;
            ILayer pLayer;
            for (int i = 0; i < index; i++)
            {
                pLayer = axMapControl1.get_Layer(i);
                if (pLayer.Name == name)
                {
                    axMapControl1.Map.DeleteLayer(pLayer);
                    axMapControl1.Refresh();
                    return;
                }

            }

        }

        private string GetMapUnit(AxMapControl axMapControl)
        {
            esriUnits mapUnits = axMapControl.MapUnits;
            switch (mapUnits)
            {
                case esriUnits.esriCentimeters:
                    return "厘米";
                case esriUnits.esriDecimalDegrees:
                    return "度";
                case esriUnits.esriDecimeters:
                    return "分米";
                case esriUnits.esriFeet:
                    return "厘米";
                case esriUnits.esriInches:
                    return "英寸";
                case esriUnits.esriKilometers:
                    return "千米";
                case esriUnits.esriMeters:
                    return "米";
                case esriUnits.esriMiles:
                    return "英里";
                case esriUnits.esriMillimeters:
                    return "毫米";
                case esriUnits.esriNauticalMiles:
                    return "海里";
                case esriUnits.esriPoints:
                    return "点";
                case esriUnits.esriUnknownUnits:
                    return "未知";
                case esriUnits.esriYards:
                    return "码";
                default:
                    return "未知";
            }
        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            e.Node.Expand();

            string name;

            //此树节点没有子节点，并且点击前已经被选中
            if (e.Node.Nodes.Count == 0 && e.Node.Checked == false)
            {
                name = e.Node.Text;
                DeletedLayer(name);
                subParentUnchecked(e.Node);
            }

            //此树节点没有子节点，并且点击前未被选中
            if (e.Node.Nodes.Count == 0 && e.Node.Checked == true)
            {
                name = e.Node.Text;
                ConnectSDE connectSDE = new ConnectSDE();
                pWorkspace = connectSDE.SdeWorkspace();

                ILayer pLayer;
                for (int n = 0; n < axMapControl1.Map.LayerCount; n++)
                {
                    pLayer = axMapControl1.Map.get_Layer(n);
                    if (e.Node.Text == pLayer.Name) return;
                }
                if (e.Node.Tag.ToString() == "2")
                {
                    SearchFeatureDataset(name, pWorkspace);
                }
                else if (e.Node.Tag.ToString() == "1")
                {
                    SearchRasterDataset(e.Node.Parent.Text, name, pWorkspace);
                }
                subParentChecked(e.Node);
            }

            //此树节点有子节点，地点后的状态为选中
            if (e.Node.Nodes.Count != 0 && e.Node.Checked == true)
            {
                //防止只有一个子节点时弹出两次警告窗口
                if (e.Node.Nodes.Count == 1)
                {
                    foreach (TreeNode subNode in e.Node.Nodes)
                    {
                        if (subNode.Checked == true)
                            return;
                    }
                }

                foreach (TreeNode subNode in e.Node.Nodes)
                {
                    if (subNode.Checked == false)
                    {
                        subNode.Checked = true;
                    }
                }
                //}
            }

            //有子节点，并且点击后的状态为取消
            if (e.Node.Nodes.Count != 0 && e.Node.Checked == false)
            {

                foreach (TreeNode subNode in e.Node.Nodes)
                {
                    if (subNode.Checked == true)
                    {
                        subNode.Checked = false;
                    }
                }
            }
        }

        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;
            node.Nodes.Clear();  //删除建立父节点时产生的那个任意子节点

            string name;
            name = node.Text;

            ConnectSDE connectSDE = new ConnectSDE();
            pWorkspace = connectSDE.SdeWorkspace();

            //判断展开的节点是要素集还是栅格目录，怎么判断？？？
            if (e.Node.Tag.ToString() == "1")
            {
                IRasterWorkspaceEx pRasterWorkspaceEx = pWorkspace as IRasterWorkspaceEx;
                IRasterCatalog pRasterCatalog = pRasterWorkspaceEx.OpenRasterCatalog(e.Node.Text);
                ITable pTable = pRasterCatalog as ITable;
                int index = pTable.FindField("NAME");

                IRow pRow = null;
                ICursor pRasterCursor = pTable.Search(null, false);
                pRow = pRasterCursor.NextRow();
                while (pRow != null)
                {
                    name = pRow.get_Value(index).ToString();
                    TreeNode subNode = new TreeNode(name);
                    node.Nodes.Add(subNode);
                    subNode.Tag = 1;
                    subNode.ImageIndex =3;
                    subNode.SelectedImageIndex = 3;
                    pRow = pRasterCursor.NextRow();
                }
            }
            else if (e.Node.Tag.ToString() == "2")
            {
                IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;
                IFeatureDataset pFeatureDataset;
                pFeatureDataset = pFeatureWorkspace.OpenFeatureDataset(name);

                IEnumDataset pEnumDataset;
                pEnumDataset = pFeatureDataset.Subsets;
                pEnumDataset.Reset();

                IDataset pDataset;
                pDataset = pEnumDataset.Next();
                while (pDataset != null)
                {
                    name = pDataset.Name;
                    TreeNode subNode = new TreeNode(name);
                    subNode.Tag = 2;
                    subNode.ImageIndex = 2;
                    subNode.SelectedImageIndex = 2;
                    node.Nodes.Add(subNode);
                    pDataset = pEnumDataset.Next();
                }
            }
        }

        #endregion

        #region 查询

        private void attributreQuery_ItemClick(object sender, ItemClickEventArgs e)
        {
            QueryFrm queryFrm = new QueryFrm(axMapControl1);
            queryFrm.Show();
        }

        #endregion

        #region 视图

        private void databaseDirHideBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            splitContainerControl1.Panel2.Visible = false;
            splitContainerControl1.Panel1.Dock = DockStyle.Fill;

        }

        private void databaseDirShowBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            splitContainerControl1.Panel1.Dock = DockStyle.None;
            splitContainerControl1.Panel2.Visible = true;
        }

        #endregion

        #region 入库
        private void controlPointEditBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            InputeControlPoints inputeFrm = new InputeControlPoints();
            inputeFrm.Show();
        }

        private void controlPointUpdateBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            UpdateControlPoints updateFrm = new UpdateControlPoints();
            updateFrm.Show();
        }

        private void controlPointImportBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ImportControlPointFrm importPoint = new ImportControlPointFrm();
            importPoint.Show();
        }

        private void rasterImportBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            ImportRaster importRaster = new ImportRaster();
            importRaster.Show();
        }
        #endregion

        private void clipRasterBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            RasterClipFrm rasterClip = new RasterClipFrm(this, this.axMapControl1);
            rasterClip.Owner = this;
            rasterClip.Show();

        }

        private void overlayBtnItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            overlayFrm overlayFrm = new overlayFrm();
            overlayFrm.Show();
        }

        private void zoomInFixedBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            IEnvelope pEnvelope = null;
            pEnvelope = axMapControl1.Extent;
            pEnvelope.Expand(0.5, 0.5, true);
            axMapControl1.Extent = pEnvelope;
        }

        private void zoomOutFixedBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            IEnvelope pEnvelop = axMapControl1.Extent;
            pEnvelop.Expand(2, 2, true);
            axMapControl1.Extent = pEnvelop;
        }

        private void selectBtn_ItemClick(object sender, ItemClickEventArgs e)
        {
            SelectClass selectClass = new SelectClass(axMapControl1);
            selectClass.OnCreate(axMapControl1 );
            axMapControl1.CurrentTool = selectClass as ITool;
        }




    }
}